package com.sweet.util;

import com.sweet.enums.Charset;
import com.sweet.lang.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;

import java.io.UnsupportedEncodingException;

/**
 * 编码、解码工具类
 *
 * @author limi
 * @version 2015-11-30
 */
@Slf4j
public final class CodeUtil {
    private static final String CHARSET = Charset.UTF8.getCharset();

    private CodeUtil() {
    }

    /**
     * 编码
     *
     * @param source
     * @return
     */
    public static String encode(final String source) {
        if (StringUtil.isEmpty(source)) {
            return source;
        }

        try {
            return java.net.URLEncoder.encode(source, CHARSET);
        } catch (UnsupportedEncodingException e) {
            log.error("encode failure!", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 解码
     *
     * @param source
     * @return
     */
    public static String decode(final String source) {
        if (StringUtil.isEmpty(source)) {
            return source;
        }

        try {
            return java.net.URLDecoder.decode(source, CHARSET);
        } catch (UnsupportedEncodingException e) {
            log.error("decode failure!", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 常用字符转码<br/>
     * 将ISO-8859-1转为UTF-8
     *
     * @param data
     * @return
     */
    public static String convertCharset(final String data) {
        return convertCharset(data, Charset.ISO88591, Charset.UTF8);
    }

    /**
     * 字符串转换编码
     *
     * @param data
     * @param fromCharset
     * @param toCharset
     * @return
     */
    public static String convertCharset(final String data, Charset fromCharset, Charset toCharset) {
        if (StringUtil.isEmpty(data)) {
            return data;
        }

        try {
            return new String(data.getBytes(fromCharset.getCharset()), toCharset.getCharset());
        } catch (UnsupportedEncodingException e) {
            log.error("convertCharset failure!", e);
            throw new RuntimeException(e);
        }
    }
}
